$(function () {
    //封装方法
    show();
    calc();
    var r ;
    function show(){
        var uid=sessionStorage.getItem("userId");
        var data={"userId":uid};
        $.post("/shoppingcart/listBay",data,function(result){
            //清空原来,保留头部信息
            r=result.shoppingcartList;
            $("#shopping  .bd tr").remove();
            for (var i = 0; i < r.length; i++) {
                var totalPrice=r[i].goods.price*1.1;
                $("#shopping tbody").append('<tr id="product1"><td class="cart_td_1"><input name="cartCheckBox" type="checkbox" value="product1"/></td><td class="cart_td_2"><img src="'
                    +r[i].goods.gimage+'" width="80" height="80" alt="shopping"/></td><td class="cart_td_3"><a href="#">'
                    +r[i].goods.gname+'</td> <td class="cart_td_4">'
                    +totalPrice.toFixed(2)+'</td> <td class="cart_td_5">'
                    +r[i].goods.price.toFixed(2)+'</td><td class="cart_td_6"><img src="/images/taobao_minus.jpg" alt="minus" class="hand"/> <input id="num_1" type="text"  value="'
                    +r[i].subtotal+'" class="num_input" readonly="readonly"/> <img src="/images/taobao_adding.jpg" alt="add" class="hand"/></td><td class="cart_td_7">'
                    +r[i].totalCount.toFixed(2)+'</td><td class="cart_td_8"><a href="javascript:void(0);" onclick ="return confirm('+"是否删除？"+')" class="aa">删除</a><br/><a href="javascript:void(0);" class="shou">收藏</a></td></tr>');
            }
            /*计算开始*/
            calc();
            /*计算结束*/
            //删除
            $(".aa").click(function(){
                //一种
                var ind=$(this).parents("#shopping tbody tr").index();
                var id=r[ind].id;
                var json={"id":id};
                var flag = confirm('是否删除？');
                if (flag) {
                    $.post("/shoppingcart/del",json,function(r){
                        if(r=="ok"){
                            alert("删除成功！");
                        }else{
                            alert("删除失败！");
                        }

                        //刷新表格
                        show();

                    },"text");
                }


            });
            //收藏
            $(".shou").click(function(){
                //一种
                var ind=$(this).parents("#shopping tbody tr").index();
                var g_ID=r[ind].goods.gid;
                var json={"gid":g_ID};
                $.post("/collect/addLike",json,function(r){
                    if(r=="ok"){
                        alert("收藏成功！！！！！");
                    }else if (r=="err") {
                        var flag =confirm('请登陆！！！！！！！');
                        if (flag) {
                            window.location.href="/qd/login.jsp";
                        }

                    }else{
                        alert("收藏失败！！！！！！！！！");


                    }

                },"text");
            });
            //增加商品数量
            //点击添加商品
            $("img[alt=add]").click(function(){
                var ind=$(this).parents("#shopping tbody tr").index();
                var id=r[ind].id;
                var number=r[ind].subtotal;
                var tocal=r[ind].totalCount.toFixed(2);
                var g_Price=r[ind].goods.price.toFixed(2);
                var json={"id":id,
                    "subtotal":number,
                    "totalCount":tocal,
                    "totalPrice":g_Price};
                var conditionDataJSON = JSON.stringify(json);
                console.log(json);
                $.ajax({
                    type: 'post',
                    dataType: 'json',
                    url: '/shoppingcart/Addsnumber',
                    data: conditionDataJSON,
                    contentType: "application/json",
                    cache: false,
                    async: true,
                    success: function (data) {
                        var m=$(this).siblings().val();
                        //判断
                        if (m>1) {m--;}
                        //显示 改变
                        $(this).siblings().val(m);
                        show();
                    }
                });
            });

            //减去商品-判断m 不能小于1
            $("img[alt=minus]").click(function(){
                var ind=$(this).parents("#shopping tbody tr").index();
                var id=r[ind].id;
                var number=r[ind].subtotal;
                var tocal=r[ind].totalCount.toFixed(2);
                var g_Price=r[ind].goods.price.toFixed(2);
                var json={"id":id,
                    "subtotal":number,
                    "totalCount":tocal,
                    "totalPrice":g_Price};
                var conditionDataJSON = JSON.stringify(json);
                $.ajax({
                    type: 'post',
                    dataType: 'json',
                    url: '/shoppingcart/reduceShopping',
                    data: conditionDataJSON,
                    contentType: "application/json",
                    cache: false,
                    async: true,
                    success: function (data) {
                        var n =$(this).prev().val();
                        n++;
                        //显示 改变
                        $(this).prev().val(n);
                        show();
                    }

            });

            });


            $("input[name=cartCheckBox]").click(function(){
                //初始状态默认全选
                $("#allCheckBox").attr("checked","checked");
                //遍历所有的name=cartCheckBox
                $("input[name=cartCheckBox]").each(function(){
                    //有一个没选中
                    if ($(this).attr("checked")!="checked") {
                        //让全部不选中
                        $("#allCheckBox").removeAttr("checked");
                        //退出循环 each break会失效
                        return false;

                    };
                });
                calc();
            });

        },"json");



    }
    //全选全不选
    $("#allCheckBox").click(function(){
        var a =$(this).attr("checked");
        //移除
        $("input[name=cartCheckBox]").removeAttr("checked").attr("checked",a);
        calc();
    });

    //删除商品
    $(".cart_td_8").find(".delShopping").click(function(){
        //$(this).parent().parent().prev().remove();//删除前tr
        $(this).parent().parent().remove();//删除当前
        show();
    });

    //删除所选
    $("#deleteAll img[alt=delete]").click(function() {
        var ids = [];
        var flag = confirm('是否删除？');
        if (flag) {
            var f = false;
            //遍历循环复选框
            $("input[name=cartCheckBox]").each(function (i, dom) {
                //判断是否选中
                if ($(dom).attr("checked")) {
                    var ind = $(this).parents("#shopping tbody tr").index();
                    var id = r[ind].id;
                    ids.push(id);
                    //数组转字符串
                    //让全部不选中
                    $("#allCheckBox").removeAttr("checked");
                    f = true;
                }

            });
            if (f == false) {
                alert("请选择删除对象！！！！！！！！！！");
                return;
            }
            var idss = ids.join(",")
            var d = {"idss": idss}
            console.log(d);
            $.post("/shoppingcart/dels", d, function (r) {
                if (r.flag == true) {
                    alert("删除成功，删除了" + r.count + "条数据！！！！");
                    //刷新表格
                    $(this).parents("tr").remove();
                    show();
                    return;
                } else {
                    alert("删除失败！！！！！！！！！");
                    return;

                }

            }, "json");
        }
    });


    function calc() {
        var total =0;
        var totaljifen =0;
        //alert($("tr[id]").length)
        //i--下标
        //dom--dui对象本身this
        //循环 jQuery  .each()
        //计算总价 累加器
        $("tr[id]").each(function(i,dom){
            var price =$(dom).children(".cart_td_5").html()*1;
            //var jifen =$(dom).children(".cart_td_4").html();
            var jifen =0;
            //购买数量
            var num =$(dom).children(".cart_td_6").children("input").val();
            //某个商品价格=单价*数量
            var sum =price * num;
           // console.log(sum);
            //显示商品保留小数点的后两位
            $(dom).children(".cart_td_7").html(sum.toFixed(2));
            //判断是否选中
            if ($(dom).find("[name='cartCheckBox']").attr("checked")){

                total+=sum;
                jifen =num*1;
                totaljifen += jifen;

            }
        });
        //显示总价
        $("#shopping tfoot tr .shopend label#total").html(total.toFixed(2));
        $("#shopping tfoot tr .shopend label#integral").html(totaljifen);
        $("#shopping tfoot tr .shopend input#totalA").val(total.toFixed(2));
        $("#shopping tfoot tr .shopend input#numberA").val(totaljifen);

    }


});
